import { GetCartList } from '../../api/cart'

export const types = {
	GET_CART_LIST: 'Cart/GetCartIndexList',
	SET_CART_LIST: 'setCartList',
	CART_JIA: 'Cart/setcartJia',
	CART_JIAN: 'Cart/setcarJian',
	CART_SUM_CHECK: 'Cart/setCartSumCheck',
	CART_ITEM_CHECK: 'Cart/setCartItemCheck',
	CART_SUM_PRICE: 'Cart/setCartPrice'
}

export const actions = {
	getCartList() {
		return {
			type: types.GET_CART_LIST,
		}
	},
	cartJia(data: any) {
		return {
			type: types.CART_JIA,
			data
		}
	},
	cartJian(data: any) {
		return {
			type: types.CART_JIAN,
			data
		}
	},
	sumCheck(data: any) {
		return {
			type: types.CART_SUM_CHECK,
			data
		}
	},
	itemCheck(data: any) {
		return {
			type: types.CART_ITEM_CHECK,
			data
		}
	},
	cartPrice() {
		return {
			type: types.CART_SUM_PRICE,
		}
	}
}

export default {
	namespace: 'Cart',
	state: {
		Cartlist: [],
		sumprice: 0,
		sumcheck: false,
	},
	reducers: {
		setCartList(state: any, action: any) {
			state.Cartlist = action.car.data.data
			state.Cartlist.forEach((item: any) => {
				item['checkflag'] = false
			})
			console.log(state.Cartlist)
			return { ...state }
		},
		setcartJia(state: any, action: any) {
			state.Cartlist.forEach((item: any) => {
				if (item.id == action.data) {
					item.buy_num++
				}
			})
			return { ...state }
		},
		setcarJian(state: any, action: any) {
			state.Cartlist.forEach((item: any) => {
				if (item.id == action.data) {
					item.buy_num--
					if (item.buy_num <= 0) {
						let index = state.Cartlist.findIndex((i: any) => i.id == item.id)
						state.Cartlist.splice(index, 1)
					}
				}
			})
			return { ...state }
		},
		setCartSumCheck(state: any, action: any) {
			state.sumcheck = action.data
			state.Cartlist.forEach((item: any) => {
				item.checkflag = action.data
			})
			return { ...state }
		},
		setCartItemCheck(state: any, action: any) {
			state.Cartlist.forEach((i: any) => {
				if (i.id === action.data.item.id) {
					// console.log(action.data.checke)
					i.checkflag = action.data.checke
				}
			})
			state.sumcheck = state.Cartlist.every((item: any) => item.checkflag)
			return { ...state }
		},
		setCartPrice(state: any, action: any) {
			state.sumprice = state.Cartlist.filter((item: any) => item.checkflag).reduce((tag: any, item: any) => {
				return (tag * 10000 + (item.buy_num * item.goods_price) * 10000) / 10000
			}, 0)
			return { ...state }
		}
	},
	effects: {
		*GetCartIndexList({ }, { call, put }: { call: any, put: any }) {
			let car = yield call(GetCartList)
			// console.log('car:------', car)
			yield put({ type: types.SET_CART_LIST, car })
		}
	}
}
